package com.bicycle.wxpublic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.*;
import com.bicycle.common.helper.GenratorNoHelper;
import com.bicycle.service.entity.*;
import com.bicycle.service.mapper.*;
import com.bicycle.wxpublic.handle.DownloadPictureThread;
import com.bicycle.wxpublic.service.EnterpriseService;
import com.bicycle.wxpublic.service.RegionService;
import com.bicycle.wxpublic.service.ReportService;
import com.bicycle.wxpublic.service.WeChatService;
import com.bicycle.wxpublic.vo.ReportPhotoDto;
import com.bicycle.wxpublic.vo.ReportRecordDetailVo;
import com.bicycle.wxpublic.vo.ReportRecordDto;
import com.bicycle.wxpublic.vo.ReportRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author : layne
 * @Date: 2020/8/7
 * @Time: 22:41
 * Description:
 */
@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private RegionService regionService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private BicycleSequenceReportRecordMapper reportRecordMapper;
    @Autowired
    private BicycleSequenceReportDetailMapper reportDetailMapper;
    @Autowired
    private BicycleSequenceReportPhotoMapper reportPhotoMapper;
    @Autowired
    private BicycleSequenceReportProcessMapper reportProcessMapper;
    @Autowired
    private BicycleCommonFileMapper fileMapper;

    @Autowired
    private Environment environment;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message photoReport(ReportPhotoDto reportPhotoDto) {
        Message message = new Message();

        // 生成举报记录
        BicycleSequenceReportRecord bicycleSequenceReportRecord = new BicycleSequenceReportRecord();
        BeanUtil.copyProperties(reportPhotoDto, bicycleSequenceReportRecord);
        bicycleSequenceReportRecord.setCreateTime(new Date());
        bicycleSequenceReportRecord.setReportTime(new Date());
        bicycleSequenceReportRecord.setReportType(StringUtils.join(reportPhotoDto.getReportType(), ","));

        // 默认不是违规投放
        bicycleSequenceReportRecord.setHasViolation(HasViolationEnum.HAS_VIOLATION_FALSE.getKey());
        // 默认未处理状态
        bicycleSequenceReportRecord.setReportStatus(ReportStatusEnum.REPORT_STATUS_0.getKey());
        String reportNo = GenratorNoHelper.generateReportNo();
        bicycleSequenceReportRecord.setReportNo(reportNo);

        BicycleCommonRegion region = regionService.getRegion(reportPhotoDto.getDistrictId());
        bicycleSequenceReportRecord.setDistrictName(region.getRegionName());
        //只有政府用户才能进行举报
        bicycleSequenceReportRecord.setReportResource(ReportResourceEnum.GOV.getKey());
        reportRecordMapper.insert(bicycleSequenceReportRecord);
        int reportId = bicycleSequenceReportRecord.getReportId();

        // 拆分举报记录
        for (int i = 0; i < reportPhotoDto.getEnterpriseNos().length; i++) {

            // 不做合法车辆举报
            BicycleSequenceReportDetail bicycleSequenceReportDetail = new BicycleSequenceReportDetail();
            BeanUtil.copyProperties(reportPhotoDto, bicycleSequenceReportDetail);
            BeanUtil.copyProperties(bicycleSequenceReportRecord, bicycleSequenceReportDetail);
            bicycleSequenceReportDetail.setCreateTime(new Date());

            // 其他非法企业
            if (StringUtils.equalsIgnoreCase("075599", reportPhotoDto.getEnterpriseNos()[i])) {
                bicycleSequenceReportDetail.setEnterpriseNo("075599");
                bicycleSequenceReportDetail.setEnterpriseName("其它");
            } else {
                BicycleCommonEnterprise enterprise = enterpriseService.getEnterprise(reportPhotoDto.getEnterpriseNos()[i]);
                bicycleSequenceReportDetail.setEnterpriseName(enterprise.getEnterpriseAlias());
                bicycleSequenceReportDetail.setEnterpriseNo(enterprise.getEnterpriseNo());
            }
            bicycleSequenceReportDetail.setHasTrue(0);
            // 默认未处理
            bicycleSequenceReportDetail.setReportStatus(ReportStatusEnum.REPORT_STATUS_0.getKey());
            bicycleSequenceReportDetail.setUpdateTime(new Date());
            bicycleSequenceReportDetail.setHasIntelligence(0);
            reportDetailMapper.insert(bicycleSequenceReportDetail);
            int detailId = bicycleSequenceReportDetail.getDetailId();
            // 处理图片线程
            if (reportPhotoDto.getReportMediaId() != null && reportPhotoDto.getReportMediaId().length > 0) {
                new DownloadPictureThread(null, null, reportPhotoDto.getReportMediaId(), reportPhotoMapper, detailId,
                        null, fileMapper, weChatService, environment.getProperty("file.upload.path"),
                        environment.getProperty("file.download.path"), environment).start();
            }
        }
        message.setResult(bicycleSequenceReportRecord);
        return message;
    }

    @Override
    public Message record(ReportRecordDto reportRecordDto) {
        Message message = new Message();
        Date endDate = new Date();
        Date beginDate = null;
        if (reportRecordDto.getDayCriteria() == 2) {
            // 七天
            beginDate = DateUtil.offsetDay(endDate, -7);
        }
        if (reportRecordDto.getDayCriteria() == 3) {
            // 一个月
            beginDate = DateUtil.offsetMonth(endDate, -1);
        }
        if (reportRecordDto.getDayCriteria() == 4) {
            // 三个月
            beginDate = DateUtil.offsetMonth(endDate, -3);
        }
        QueryWrapper<BicycleSequenceReportRecord> queryWrapper = new QueryWrapper<BicycleSequenceReportRecord>();
        BicycleSequenceReportRecord bicycleSequenceReportRecord = new BicycleSequenceReportRecord();
        bicycleSequenceReportRecord.setUserId(reportRecordDto.getUserId());
        queryWrapper.setEntity(bicycleSequenceReportRecord);
        if (beginDate != null && endDate != null) {
            queryWrapper.between("report_time", beginDate, endDate);
        }


        queryWrapper.orderByDesc("report_time");
        List<BicycleSequenceReportRecord> bicycleSequenceReportRecords = reportRecordMapper.selectList(queryWrapper);


        List<ReportRecordVo> reportRecordResps = new ArrayList<>();
        bicycleSequenceReportRecords.forEach(rtcSequenceUserReportRecord -> {
            ReportRecordVo reportRecordResp = new ReportRecordVo();
            BeanUtil.copyProperties(rtcSequenceUserReportRecord, reportRecordResp);
            if (StringUtils.isNotBlank(rtcSequenceUserReportRecord.getReportType())) {
                reportRecordResp.setReportType(rtcSequenceUserReportRecord.getReportType().split(","));
            }
            reportRecordResp.setIsViolation(rtcSequenceUserReportRecord.getHasViolation());
            reportRecordResps.add(reportRecordResp);
        });
        message.setResult(reportRecordResps);
        return message;
    }

    @Override
    public Message recordDetail(Integer reportId) {
        Message message = new Message();
        ReportRecordDetailVo reportRecordDetailVo = new ReportRecordDetailVo();
        BicycleSequenceReportRecord userReportRecord = reportRecordMapper.selectById(reportId);
        QueryWrapper<BicycleSequenceReportDetail> queryWrapper = new QueryWrapper<BicycleSequenceReportDetail>();
        BicycleSequenceReportDetail sequenceReportDetail = new BicycleSequenceReportDetail();
        sequenceReportDetail.setReportId(userReportRecord.getReportId());
        queryWrapper.setEntity(sequenceReportDetail);
        List<BicycleSequenceReportDetail> sequenceReportDetails = reportDetailMapper.selectList(queryWrapper);

        // 非法车辆编号
        List<String> illegal = new ArrayList<>();
        // 合法车辆编号
        List<String> legal = new ArrayList<>();
        List<ReportRecordDetailVo.ReportRecordReportDetailVo> reportDetail = new ArrayList<>();

        // 总体结案时间
        Date closeTime = null;
        List<Integer> detailIds = new ArrayList<>();
        for (BicycleSequenceReportDetail bicycleSequenceReportDetail : sequenceReportDetails) {
            detailIds.add(bicycleSequenceReportDetail.getDetailId());
            ReportRecordDetailVo.ReportRecordReportDetailVo reportRecordReportDetailVo = new ReportRecordDetailVo.ReportRecordReportDetailVo();
            BeanUtil.copyProperties(bicycleSequenceReportDetail, reportRecordReportDetailVo);

            Map<String, Object> detail = new HashMap<String, Object>();

            //拍照举报没有具体车辆数据信息
            // 合法车辆
            reportRecordReportDetailVo.setLegal(0);
            // 非法车辆
            reportRecordReportDetailVo.setIllegal(0);
            QueryWrapper<BicycleSequenceReportProcess> processQueryWrapper = new QueryWrapper<BicycleSequenceReportProcess>();
            BicycleSequenceReportProcess qProcessRecord = new BicycleSequenceReportProcess();
            qProcessRecord.setDetailId(bicycleSequenceReportDetail.getDetailId());
            qProcessRecord.setOperateType(1);
            processQueryWrapper.setEntity(qProcessRecord);
            processQueryWrapper.orderByDesc("create_time");
            BicycleSequenceReportProcess detailProcessRecord = reportProcessMapper.selectOne(processQueryWrapper);

            // 已结案 赋值处理时间
            if (bicycleSequenceReportDetail.getReportStatus() == 3) {
                reportRecordReportDetailVo.setProcessTime(Optional.ofNullable(detailProcessRecord).map(time -> detailProcessRecord.getProcessTime()).orElse(null));
                if (userReportRecord.getReportStatus() == 1) {
                    if (closeTime == null) {
                        closeTime = bicycleSequenceReportDetail.getCloseTime();
                    } else {
                        if (!closeTime.after(bicycleSequenceReportDetail.getCloseTime())) {
                            closeTime = bicycleSequenceReportDetail.getCloseTime();
                        }
                    }
                }
            }
            if (StringUtils.isBlank(reportRecordDetailVo.getDetailAddress())) {
                reportRecordDetailVo.setDetailAddress(bicycleSequenceReportDetail.getDetailAddress());
            }
            if (CollectionUtil.isEmpty(reportRecordDetailVo.getImageUrl())) {

                List<String> images = new ArrayList<>();
                // 获取图片地址
                QueryWrapper<BicycleSequenceReportPhoto> reportPhotoQueryWrapper = new QueryWrapper<BicycleSequenceReportPhoto>();
                BicycleSequenceReportPhoto qDetailPhoto = new BicycleSequenceReportPhoto();
                qDetailPhoto.setDetailId(bicycleSequenceReportDetail.getDetailId());
                qDetailPhoto.setPhotoType(1);
                reportPhotoQueryWrapper.setEntity(qDetailPhoto);
                List<BicycleSequenceReportPhoto> reportDetailPhotos = reportPhotoMapper.selectList(reportPhotoQueryWrapper);
                reportDetailPhotos.forEach(reportDetailPhoto -> {
                    if (reportDetailPhoto.getFileId() != null) {
                        BicycleCommonFile commonFile = fileMapper.selectById(reportDetailPhoto.getFileId());
                        images.add(commonFile.getDownloadPath() + commonFile.getRelativePath());
                    }
                });
                reportRecordDetailVo.setImageUrl(images);

            }
            // 返回经纬度
            if (StringUtils.isBlank(reportRecordDetailVo.getLat())) {
                reportRecordDetailVo.setLat(bicycleSequenceReportDetail.getLat());
            }
            if (StringUtils.isBlank(reportRecordDetailVo.getLng())) {
                reportRecordDetailVo.setLng(bicycleSequenceReportDetail.getLng());
            }
            // 返回结案时间
            reportDetail.add(reportRecordReportDetailVo);
        }

        // 案件已结案 获取最后一条
        if (userReportRecord.getReportStatus() == 1) {
            QueryWrapper<BicycleSequenceReportProcess> processQueryWrapper = new QueryWrapper<BicycleSequenceReportProcess>();
            BicycleSequenceReportProcess qProcessRecord = new BicycleSequenceReportProcess();
            qProcessRecord.setOperateType(1);
            processQueryWrapper.setEntity(qProcessRecord);
            processQueryWrapper.in("detail_id", detailIds);
            processQueryWrapper.orderByDesc("create_time");
            BicycleSequenceReportProcess detailProcessRecord = reportProcessMapper.selectOne(processQueryWrapper);


            if (detailProcessRecord != null) {
                reportRecordDetailVo.setProcessRemark(detailProcessRecord.getRemark());

                QueryWrapper<BicycleSequenceReportPhoto> reportPhotoQueryWrapper = new QueryWrapper<BicycleSequenceReportPhoto>();
                BicycleSequenceReportPhoto qDetailPhoto = new BicycleSequenceReportPhoto();
                qDetailPhoto.setDetailId(detailProcessRecord.getDetailId());
                qDetailPhoto.setPhotoType(3);
                reportPhotoQueryWrapper.setEntity(qDetailPhoto);
                List<BicycleSequenceReportPhoto> reportDetailPhotos = reportPhotoMapper.selectList(reportPhotoQueryWrapper);

                List<String> images = new ArrayList<>();
                reportDetailPhotos.forEach(reportDetailPhoto -> {
                    if (reportDetailPhoto.getFileId() != null) {
                        BicycleCommonFile commonFile = fileMapper.selectById(reportDetailPhoto.getFileId());
                        images.add(commonFile.getDownloadPath() + commonFile.getRelativePath());
                    }
                });
                reportRecordDetailVo.setAfterImages(images);
            }
        }

        BeanUtil.copyProperties(userReportRecord, reportRecordDetailVo);
        if (StringUtils.isNotBlank(userReportRecord.getReportType())) {
            reportRecordDetailVo.setReportType(userReportRecord.getReportType().split(","));
        } else {
            reportRecordDetailVo.setReportType(new String[0]);
        }
        reportRecordDetailVo.setIllegal(illegal);
        reportRecordDetailVo.setLegal(legal);
        reportRecordDetailVo.setReportDetail(reportDetail);
        reportRecordDetailVo.setCloseTime(closeTime);
        message.setResult(reportRecordDetailVo);
        return message;
    }
}
